// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package focus

import (
	"net"

	"circuit/kit/rh"
	"circuit/kit/rh/ns"
)

// cluster is a namespace of type ns.MapDir listing all circuit hosts.
type cluster loci

func newCluster(peer *Peer, peers PeerFunc, shutter rh.FID) *cluster {
	return (*cluster)(newLoci(peer, peers, shutter))
}

func (c *cluster) Map() map[string]ns.Dir { // If Map panics, the panic will be reported as ErrIO to RH, and subsequently syscall.EIO to FUSE.
	bulk := c.peers()
	dir := make(map[string]ns.Dir)
	for _, peer := range bulk {
		hname := hostfrom(peer.Kin.X.Addr().NetAddr())
		//
		d, ok := dir[hname]
		if !ok {
			d = newHost(c.peer, c.shutter)
			dir[hname] = d
		}
		h := d.(*host)
		h.peers = append(h.peers, peer)
	}
	return dir
}

func hostfrom(na net.Addr) string {
	var src = []byte(na.(*net.TCPAddr).IP.String())
	// for i, b := range src {
	// 	switch b {
	// 	case ':', '/', '"', '(', ')':
	// 		src[i] = '_'
	// 	}
	// }
	return string(src)
}

// host
type host struct {
	*loci
	peers []*Peer
}

func newHost(peer *Peer, shutter rh.FID) *host {
	h := &host{}
	h.loci = newLoci(peer, func() []*Peer {
		return h.peers
	}, shutter)
	return h
}
